package com.yixinsoft.basic.model.manage.system;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * Created by hqy on 2016/06/05
 */
@Table(name = "sys_role")
public class Role implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id; //编号
	
	@Column(name = "role_name")
	private String roleName; //角色标识 程序中判断使用,如"admin"
	
	private String description; //角色描述,UI界面显示使用
	
	@Column(name = "resource_ids")
	private String resourceIds;
	
	@Transient
	private List<Long> resources; //拥有的资源
	
	private Boolean available = Boolean.TRUE; //是否可用,如果不可用将不会添加给用户

	public Role() {
		super();
	}

	public Role(String roleName, String description, Boolean available) {
		super();
		this.roleName = roleName;
		this.description = description;
		this.available = available;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public List<Long> getResources() {
		if (resources == null) {
			resources = new ArrayList<>();
		}
		return resources;
	}

	public void setResources(List<Long> resources) {
		this.resources = resources;
	}
	
	public String getResourceIds() {
		if (CollectionUtils.isEmpty(resources)) {
			return "";
		}
		StringBuilder s = new StringBuilder();
		for (Long resourceId : resources) {
			s.append(resourceId);
			s.append(",");
		}
		return s.toString();
	}
	
	public void setResourceIds(String resourceIds) {
		if (StringUtils.isEmpty(resourceIds)) {
			return;
		}
		String[] resourceIdStrs = resourceIds.split(",");
		for (String resourceIdStr : resourceIdStrs) {
			if (StringUtils.isEmpty(resourceIdStr)) {
				continue;
			}
			getResources().add(Long.valueOf(resourceIdStr));
		}
	}

	public Boolean getAvailable() {
		return available;
	}

	public void setAvailable(Boolean available) {
		this.available = available;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Role other = (Role) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
}
